package com.example.moneygrosService;

import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.moneygrosService.CommunicationManagerService.LocalBinder;

public class PublishBT extends Activity implements OnClickListener {
	private static final String TAG = PublishBT.class.getSimpleName();

	public static final int REQUEST_ENABLE_BT = 2;

	private boolean mBound = false;
	private CommunicationManagerService mService;
	
	private Button publish_Button;
	public PublishBT() {
		// TODO Auto-generated constructor stub

	} 
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		Log.d(TAG, "onCreate");

		super.onCreate(savedInstanceState);

		setContentView(R.layout.publish_layout);

		if(BluetoothAdapter.getDefaultAdapter() != null){
			TextView publish_myBTAdress = (TextView)findViewById(R.id.publish_myAdress);
			publish_myBTAdress.setText("My address: "+ BluetoothAdapter.getDefaultAdapter().getAddress());
		}
		
		EditText publish_user_bluetooth_mac_EditText = (EditText)findViewById(R.id.publish_user_bluetooth_mac);
		publish_user_bluetooth_mac_EditText.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				EditText eText = (EditText)v;
				String str=eText.getText().toString();
				if(isCorrectBtMAC(str)){
					eText.setTextColor(Color.BLACK);
				} else {
					eText.setTextColor(Color.RED);
				}
			}

			boolean isCorrectBtMAC(String s){		    
//				String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
				String expression = "^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$";
				CharSequence inputStr = s;

				Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
				Matcher matcher = pattern.matcher(inputStr);
				return matcher.matches();
			}
		});


		publish_Button = (Button) findViewById(R.id.publish_publish_button);
		publish_Button.setEnabled(false);
		publish_Button.setOnClickListener(this);
		
		setBluetooth();
	}

    @Override
    protected void onStart() {
        super.onStart();
        // Bind to CommunicationManagerService
        Intent intent = new Intent(this, CommunicationManagerService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }
    

    @Override
    protected void onStop() {
        super.onStop();
        // Unbind from the CommunicationManagerService service
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
    }
    
    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            LocalBinder binder = (LocalBinder) service;
            mService = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };
    
	private void setBluetooth() {
		// TODO Auto-generated method stub
		BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (mBluetoothAdapter == null) {
		    // Device does not support Bluetooth
			this.finish();
		} else {

			if (!mBluetoothAdapter.isEnabled()) {
				publish_Button.setEnabled(false);
				Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
			} else {
				//			try {
				//				mBluetoothAdapter.listenUsingRfcommWithServiceRecord("toto", MONEYGROS_BT_SERVICE_UUID);
				//			} catch (IOException e) {
				//				// TODO Auto-generated catch block
				//				e.printStackTrace();
				//			}

				publish_Button.setEnabled(true);
			}
		}

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_ENABLE_BT) {
			if(resultCode == RESULT_OK){
				setBluetooth();
			}

			if (resultCode == RESULT_CANCELED) {
				this.finish();
			}
		}
	}

	@Override
	public void onClick(View arg0) {

		if(mBound){
			Log.d(TAG, "envoi de message");
			mService.sendMessage((String)((EditText)findViewById(R.id.publish_user_bluetooth_mac)).getText().toString().toUpperCase());
		}


		this.finish();
	}


}
